package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.dto.ArticleStreamMessage;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.task.ArticleHtmlTasks;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author hsg
 * @since 2022-06-31
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {
    @Autowired
    private IApArticleContentService apArticleContentService;
    @Autowired
    private ArticleHtmlTasks articleHtmlTasks;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        //id不为空代表已经存在，则修改
        if(dto.getId()!=null){
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            this.updateById(apArticle);
            LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper();
            updateWrapper.eq(ApArticleContent::getArticleId,apArticle.getId());
            updateWrapper.set(ApArticleContent::getContent,dto.getContent());
            apArticleContentService.update(updateWrapper);
            return ResponseResult.okResult(apArticle.getId());
        }else{
            //id为空，新增
            ApArticle apArticle = new ApArticle();
            BeanUtils.copyProperties(dto,apArticle);
            apArticle.setCreatedTime(new Date());
            apArticle.setId(null);
            this.save(apArticle);
            ApArticleContent apArticleContent = new ApArticleContent();
            apArticleContent.setId(null);
            apArticleContent.setArticleId(apArticle.getId());
            apArticleContent.setContent(dto.getContent());
            apArticleContentService.save(apArticleContent);
            articleHtmlTasks.createHtml(apArticle,dto.getContent());
            return ResponseResult.okResult(apArticle.getId());
        }
    }

    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
        // 首页 1 首页加载 0 非首页
        if (dto.getLoaddir()==1) {
            long start = 0L;
            long end = dto.getSize()-1;
            Set<String> strings = redisTemplate.boundZSetOps("hot_article_first_page_" + dto.getChannelId()).reverseRange(start, end);
            List<ApArticle> list = new ArrayList<>();
            for (String string : strings) {
                ApArticle apArticle = JSON.parseObject(string, ApArticle.class);
                list.add(apArticle);
            }
            if(list.size()>=dto.getSize()){
                return ResponseResult.okResult(list);
            }
        }
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        // 查询发布时间大于dto中的maxTime
        if(type==0){
            queryWrapper.gt(ApArticle::getPublishTime,dto.getMaxTime());
        }else{
            queryWrapper.lt(ApArticle::getPublishTime,dto.getMinTime());
        }
        // 如果dto中的channelId不为0时 根据频道查询
        if(dto.getChannelId()!=0){
            queryWrapper.eq(ApArticle::getChannelId,dto.getChannelId());
        }
//        两个隐藏的条件 1、是否删除 2、是否下架
        queryWrapper.eq(ApArticle::getIsDelete,false);
        queryWrapper.eq(ApArticle::getIsDown,false);
//      根据发布时间降序查询
        queryWrapper.orderByDesc(ApArticle::getPublishTime);
//      分页查询
        IPage<ApArticle> page = new Page<>(1,dto.getSize());
        IPage<ApArticle> page1 = this.page(page, queryWrapper);
        return ResponseResult.okResult(page1.getRecords());
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        // 根据id查询文章
        ApArticle apArticle = this.getById(dto.getArticleId());
        if (apArticle == null || apArticle.getIsDelete() || apArticle.getIsDown()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 根据id查询文章内容
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent articleContent = apArticleContentService.getOne(query);
        // 按照前端的格式拼接map
        Map<String, Object> map = new HashMap<>();
        map.put("config", apArticle);
        map.put("content", articleContent);
        // 返回通用的响应
        return ResponseResult.okResult(map);
    }

    @Override
    public void computeHotArticle() {
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getIsDelete,false);
        queryWrapper.eq(ApArticle::getIsDown,false);
        Date beforeDate = DateTime.now().minusDays(300).toDate();
        queryWrapper.gt(ApArticle::getPublishTime,beforeDate);
        List<ApArticle> apArticles = this.list(queryWrapper);
        for (ApArticle apArticle : apArticles) {
            Integer score =  computer(apArticle);
            //推荐数据的redis
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(JSON.toJSONString(apArticle),score);
            redisTemplate.boundZSetOps("hot_article_first_page_"+apArticle.getChannelName()).add(JSON.toJSONString(apArticle),score);

        }

    }

    @Override
    public void updateHotArticle(ArticleStreamMessage message) {
        //       1、计算文章热度值
        Long articleId = message.getArticleId();
        ApArticle article = this.getById(articleId);
        int score = computeTodayScore(message);
        ApArticle cache = new ApArticle();
        cache.setId(article.getId());
        cache.setTitle(article.getTitle());
        cache.setImages(article.getImages());
        cache.setAuthorId(article.getAuthorId());
        cache.setAuthorName(article.getAuthorName());
        cache.setLayout(article.getLayout());
        cache.setStaticUrl(article.getStaticUrl());
        //      2、更新redis
        Double scoreBefore = redisTemplate.boundZSetOps("hot_article_first_page_0").score(JSON.toJSONString(cache));
        if(scoreBefore!=null){
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(JSON.toJSONString(cache),scoreBefore+score);
            redisTemplate.boundZSetOps("hot_article_first_page_"+article.getChannelId()).add(JSON.toJSONString(cache),scoreBefore+score);
        }else{
            redisTemplate.boundZSetOps("hot_article_first_page_0").add(JSON.toJSONString(cache),score);
            redisTemplate.boundZSetOps("hot_article_first_page_"+article.getChannelId()).add(JSON.toJSONString(cache),score);
        }
        //     3、更新mysql
        LambdaUpdateWrapper<ApArticle> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ApArticle::getId,message.getArticleId());
        updateWrapper.setSql("views=views+"+message.getView());
        updateWrapper.setSql("likes=likes+"+message.getLike());
        updateWrapper.setSql("comment=comment+"+message.getComment());
        updateWrapper.setSql("collection=collection+"+message.getCollect());
        this.update(updateWrapper);

    }
    private int computeTodayScore(ArticleStreamMessage message) {
        int score = 0;
        score += message.getView() * 1 * 3;
        score += message.getLike() * 3 * 3;
        score += message.getComment() * 5 * 3;
        score += message.getCollect() * 8 * 3;
        return score;
    }
    private Integer computer(ApArticle apArticle) {
        int score=0;
        if (apArticle.getViews() != null) {
            score += apArticle.getViews() * 1;
        }
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * 3;
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * 5;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * 8;
        }
        return score;
    }
}
